package com.huanglejing.shanggou.activity

import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v4.util.ArrayMap
import com.bumptech.glide.Glide
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.huanglejing.shanggou.R
import com.huanglejing.shanggou.bean.UpdateInfo
import com.huanglejing.shanggou.common.AppContext
import com.huanglejing.shanggou.common.BaseActivity
import com.huanglejing.shanggou.data.CacheName
import com.huanglejing.shanggou.data.CachePwd
import com.huanglejing.shanggou.data.Locale_Spanish
import com.huanglejing.shanggou.presenterimpl.BaseCacheRequestImpl
import com.huanglejing.shanggou.rx.SchedulersCompat
import com.huanglejing.shanggou.rx.SimpleSubscriber
import com.huanglejing.shanggou.utils.*
import kotlinx.android.synthetic.main.activity_splash.*
import rx.Observable
import java.util.*
import java.util.concurrent.TimeUnit


class SplashActivity : BaseActivity() {
    private var updateBundle: Bundle? = null
    private val merrorStr = "{\n" +
            "    \"data\": {\n" +
            "        \"id\": \"\",\n" +
            "        \"name\": \"\"\n" +
            "    },\n" +
            "    \"status\": \"00\"\n" +
            "}"
    private val handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)
        val share = AppContext.get().getSharedPreferences(C.Preference.SAHNGOU_DATA, Context.MODE_PRIVATE)
        val resources = resources// 获得res资源对象
        val config = resources.configuration// 获得设置对象
        val dm = resources.displayMetrics// 获得屏幕参数：主要是分辨率，像素等。
        var language = share.getString(C.Preference.CACHE_LANGUAGE, "")
        if ("".equals(language) || resources.getString(R.string.str_language_zh).equals(language)) {
            config.locale = Locale.CHINA // 中文
        } else if (resources.getString(R.string.str_language_en).equals(language)) {
            config.locale = Locale.ENGLISH // 英文
        } else if (resources.getString(R.string.str_language_es).equals(language)) {
            config.locale = Locale_Spanish // 英文
        } else if (resources.getString(R.string.str_language_it).equals(language)) {
            config.locale = Locale.ITALY // 英文
        }
        resources.updateConfiguration(config, dm)

        Glide.with(this@SplashActivity).load(R.drawable.ic_login_bg)
                .placeholder(R.drawable.ic_img_error)
                .error(R.drawable.ic_img_error)
                .centerCrop().thumbnail(0.1f)
                .into(ic_splash_bg)


        updateAndLogin()


    }

    private fun updateAndLogin() {
        getUpdateParams().flatMap {
            BaseCacheRequestImpl.getInstance(C.APIV1.UPDATE)?.requestForGet(it)
        }?.map {
            AppContext.gson().fromJson<UpdateInfo>(it["data"])
        }?.timeout(2, TimeUnit.SECONDS)?.onErrorReturn { null }?.map {
            // 需要更新
            updateBundle = Bundle(1).apply {
                putSerializable(C.BundleKey.KEY1, it)
            }
        }?.map {
            ArrayMap<String, String>().apply {
                put("customerName", CacheName)
                put("password", CachePwd)
            }
        }?.flatMap {

            BaseCacheRequestImpl.getInstance(C.APIV1.LOGIN)?.requestForGet(it)?.onErrorReturn { JsonParser().parse(merrorStr).getAsJsonObject() }
        }?.delay(1000, TimeUnit.MILLISECONDS)
                ?.compose(SchedulersCompat.io())
                ?.subscribe(object : SimpleSubscriber<JsonObject>() {
                    override fun onNext(t: JsonObject) {
                        super.onNext(t)
                        if (!t.checkEmpty()) {
                            cacheLoginInfo(t?.getAsJsonObject("data")?.get("name")?.asString
                                    ?: "", t?.getAsJsonObject("data")?.get("id")?.asString ?: "")
                        }
                        if (!CacheName.checkEmpty() && !CachePwd.checkEmpty()) {
                           // cacheLoginParams(CacheName ?: "", CachePwd ?: "")
                            UIHelper.startActivity(MainActivity::class.java, updateBundle)
                        } else {
                            UIHelper.startActivity(LoginActivity::class.java, updateBundle)
                        }
                        finish()
                    }

                    override fun onError(e: Throwable) {
                        super.onError(e)
                        UIHelper.startActivity(LoginActivity::class.java, updateBundle)
                        finish()
                    }

                })?.addTo(rxManager)
    }

    private fun getUpdateParams(): Observable<Map<String, Any>> {
        var versionName = PackageHelper.getPackageInfo().versionName
        //   ToastUtils.toastLong("版本名是${versionName}")
        val ver = versionName?.replace(".", "")?.trim()?.toIntOrNull()?.toString() ?: "100"
        val map = ArrayMap<String, String>().apply {
            put("ver", ver);
            put("softname", "newandroid");
        }
        return Observable.just(map)
    }

//    private fun autoLogin(account: String, pwd: String) {
//        Observable.just()?.flatMap {
//            BaseCacheRequestImpl.getInstance(C.APIV1.LOGIN)?.requestForGet(it)
//        }?.map {
//            KLog.d("SplashActivity", "SplashActivity    ${it.toString()}")
//            AppContext.gson().fromJson<Account>(it?.get("data"))
//        }?.delay(2000, TimeUnit.MILLISECONDS)?.compose(SchedulersCompat.io())
//                ?.subscribe(object : SimpleSubscriber<Account>() {
//                    override fun onNext(t: Account) {
//                        super.onNext(t)
//                        cacheLoginInfo(t)
//                        startActivity(Intent(this@SplashActivity, MainActivity::class.java))
//                        finish()
//                    }
//
//                    override fun onError(e: Throwable) {
//                        super.onError(e)
//                        startActivity(Intent(this@SplashActivity, LoginActivity::class.java))
//                        finish()
//                    }
//
//                })?.addTo(rxManager)
//    }

    override fun onDestroy() {
        super.onDestroy()
        handler?.removeCallbacks(null)
    }
}
